package com.abbas.CayTcore.ui

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.text.Editable
import android.text.TextUtils
import android.view.View
import androidx.core.widget.addTextChangedListener
import com.abbas.CayTcore.CoreApp
import com.abbas.CayTcore.R
import com.abbas.CayTcore.adapter.CounterListAdapter
import com.abbas.CayTcore.base.BaseActivity
import com.abbas.CayTcore.databinding.ActivityCounterResultBinding
import com.abbas.CayTcore.entity.TCoreBase
import com.abbas.CayTcore.presenter.CounterResultPresenter
import com.abbas.CayTcore.view.ViewContract
import java.util.*
import kotlin.math.roundToInt


/**
 * 绕线结算界面
 * @changeDate 2023/4/22
 * @author abbas
 */
class CounterResultActivity :
    BaseActivity<ViewContract.CounterResultView, CounterResultPresenter, ActivityCounterResultBinding>(),
    ViewContract.CounterResultView {

    //当前磁芯数据
    private lateinit var core: TCoreBase

    //适配器
    private lateinit var adapter: CounterListAdapter

    //已有的磁芯个数
    private var hasWt: Float = 0f

    //目标的磁芯个数
    private var targetCount: Int = 0

    //已计算的磁芯个数
    private var itemCount: Float = 0f

    //装磁芯袋子重量
    private var packageWeight: Float = 3.3f

    //默认单重 0f
    private var dz: Float = 0f

    //？？我靠，这就是不注释的后果
    //这个变量是什么鬼
    private var jyk: Float = 0f

    override fun getViewBinding(): ActivityCounterResultBinding =
        ActivityCounterResultBinding.inflate(layoutInflater)

    override fun initPresenter(): CounterResultPresenter = CounterResultPresenter()

    override fun initData() {
        val intExtra = intent.getIntExtra("core", -1)
        if (intExtra != -1) {
            presenter.getCore(intExtra)
        }
        binding.copyEt.text = Editable.Factory.getInstance()
            .newEditable(
                CoreApp.sp.getString(CoreApp.dateStr, "")
            )
    }

    override fun initEvent() {
        //目标数量改变
        binding.targetTil.editText?.addTextChangedListener {
            it?.let {
                if (!TextUtils.isEmpty(it)) {
                    try {
                        targetCount = it.toString().toInt()
                        targetOrHasChanged()
                    } catch (e: Exception) {

                    }
                }
            }
        }
        //已持有数量改变
        binding.hasTil.editText?.addTextChangedListener {
            it?.let {
                if (!TextUtils.isEmpty(it)) {
                    hasWt = it.toString().toFloat()
                    targetOrHasChanged()
                }
            }
        }
        binding.addItem.setOnClickListener {
            binding.rv.addItem()
        }

        binding.rg.setOnCheckedChangeListener { radioGroup, i ->
            when (i) {
                R.id.y_rb -> {
                    binding.rv.hasPackage = true
                    targetOrHasChanged()
                }
                R.id.n_rb -> {
                    binding.rv.hasPackage = false
                    targetOrHasChanged()
                }
            }
        }

        binding.weight.addTextChangedListener {
            it.toString().apply {
                if (!TextUtils.isEmpty(this)) {
                    this.toFloat().apply {
                        dz = this
                        binding.rv.dz = this
                    }
                }
            }

        }

        binding.add.setOnClickListener {
            val allCountK = (hasWt * 1000 + itemCount + jyk) / 1000
            binding.copyEt.text.appendLine(core.toString() + " " + ("%.1f".format(allCountK)) + "k")
            CoreApp.sp
                .edit()
                .putString(CoreApp.dateStr, binding.copyEt.text.toString())
                .apply()
        }
        binding.removeLast.setOnClickListener {
            var split = binding.copyEt.text.toString().split("\n")
            if (split.size > 1) {
                var subList = split.subList(0, split.size - 2)
                binding.copyEt.text.clear()
                subList.forEach {
                    binding.copyEt.text.append(it + "\n")
                }
                CoreApp.sp
                    .edit()
                    .putString(CoreApp.dateStr, binding.copyEt.text.toString())
                    .apply()
            }

        }
        binding.copyIm.setOnClickListener {
            val cm: ClipboardManager =
                getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val mClipData = ClipData.newPlainText("Data", binding.copyEt.text.toString())
            cm.setPrimaryClip(mClipData)
        }

        binding.jykTil.editText?.addTextChangedListener {
            it?.let {
                val s = it.toString()
                if (s.isNotBlank()) {
                    s.toFloatOrNull()?.let { f ->
                        jyk = f * 1000
                        binding.jywTil.editText?.text =
                            Editable.Factory.getInstance()
                                .newEditable(
                                    if (binding.rv.hasPackage) {
                                        "%.2f".format((jyk * dz) - packageWeight)
                                    } else {
                                        "%.2f".format(jyk * dz)
                                    }
                                )
                    }
                }
            }
        }

    }

    override fun onCoreGet(core: TCoreBase) {
        this@CounterResultActivity.core = core
        dz = core.dz
        binding.apply {
            coreName.setText(core.toString())
            weight.setText(dz.toString())
            targetTil.editText?.setText("50")
            hasTil.editText?.setText("0")
            progress.progress = 0
            tvProgress.text = "0%"
        }
//        adapter = CounterRVAdapter(core.dz!!) { weight, counter ->
//            itemCount = counter
//            targetOrHasChanged()
//        }

        adapter = CounterListAdapter(core.dz) { weight, counter ->

        }
        binding.rv.apply {
            dz = this@CounterResultActivity.dz
            callback = {
                itemCount = it
                targetOrHasChanged()
            }
            packageWeight = this@CounterResultActivity.packageWeight
        }
    }

    private fun targetOrHasChanged() {
        //全部个数
        var hasCount = hasWt * 1000 + itemCount
        //目标个数
        var targetCountAct = targetCount * 1000
        //进度
        var progress = (hasCount / targetCountAct) * 100


        binding.progress.setProgress(progress.roundToInt(), true)
        binding.tvProgress.text = "当前进度：${progress.roundToInt()}%  ${targetCountAct/1000}k / ${"%.1f".format(hasCount / 1000)}k"
        if (progress > 100) {
            binding.ycLl.visibility = View.VISIBLE
            binding.tvProgress.setTextColor(resources.getColor(R.color.red_w) )
            var ycs = hasCount - targetCountAct
            //计算溢出数量
            binding.ycsTil.editText?.text =
                Editable.Factory.getInstance().newEditable(ycs.toString())
            //计算溢出重量
            binding.ycgTil.editText?.text =
                Editable.Factory.getInstance().newEditable((ycs * dz).toString())
        } else {
            binding.tvProgress.append(" 还需：${"%.2f".format((targetCountAct - hasCount) / 1000)}k")
            binding.tvProgress.setTextColor(resources.getColor(android.R.color.white))
            binding.ycLl.visibility = View.GONE
        }

    }

}